﻿using dTools;
using EasyLP.Client.Entity;
using System;
using System.Windows.Forms;
using System.Linq;

namespace EasyLP.Client
{
    public partial class FrmConfigForm : Form
    {
        private string _id;
        private ConfigInfo _configInfo;
        private Action _action;

        public FrmConfigForm(string id, ConfigInfo configInfo, Action action)
        {
            _id = id;
            _configInfo = configInfo;
            _action = action;

            InitializeComponent();
            this.ShowIcon = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.WindowState = FormWindowState.Normal;
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        /// <summary>
        /// 编辑 回显数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmConfigForm_Load(object sender, EventArgs e)
        {
            if (!_id.IsEmpty())
            {
                txtServerIp.Text = _configInfo.ServerIp;
                txtDesc.Text = _configInfo.Desc;
                cbShowCmd.Checked = _configInfo.ShowCMd;
                txtAppBasePath.Text = _configInfo.AppBasePath;
                cbWindows.Checked = _configInfo.WindowsOS;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var ip = txtServerIp.Text;
            var desc = txtDesc.Text;
            var showCmd = cbShowCmd.Checked;
            var appBasePath = txtAppBasePath.Text;
            if (ip.IsEmpty() || desc.IsEmpty() || appBasePath.IsEmpty())
            {
                MessageBox.Show("必填项不能为空");
                return;
            }

            _configInfo = _configInfo ?? new ConfigInfo();
            _configInfo.ServerIp = ip;
            _configInfo.Port = 5555;
            _configInfo.Desc = desc;
            _configInfo.Id = _id.IsEmpty() ? Guid.NewGuid().ToString() : _id;
            _configInfo.ShowCMd = showCmd;
            _configInfo.AppBasePath = appBasePath;
            _configInfo.WindowsOS = cbWindows.Checked;

            var allConfigs = ConfigHelper.ConfigInfos;
            var @this = allConfigs.FirstOrDefault(x => x.Id == _id);
            if (@this == null)
            {
                allConfigs.Add(_configInfo);
            }
            else
            {
                allConfigs.Remove(@this);
                allConfigs.Add(_configInfo);
            }
            ConfigHelper.ConfigInfos = allConfigs;
            _action?.Invoke();
            this.Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmConfigForm_Shown(object sender, EventArgs e)
        {
            txtServerIp.Focus();
        }
    }
}
